package com.sec;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.*;

public class Myuser implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //模拟数据库中的用户数据
    private    Map<String, com.itheima.pojo.User> map = new HashMap<>();
    private void init(){
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        // 模拟从数据库读数据
        com.itheima.pojo.User user = map.get(username);
        if (user==null){
            // 数据库中没用对应的数据
            return null;
        }
        String password = user.getPassword();
//        password = "{noop}"+password; 使用了加密就不要用这个{noop了}
        System.out.println("我执行了并且查到了数据");
        // new 一个对应的实现类,第三个参数为权限列表
        List<GrantedAuthority> list = new ArrayList<>();
//        list.add(new SimpleGrantedAuthority("haha"));
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        list.add(new SimpleGrantedAuthority("add"));
        list.add(new SimpleGrantedAuthority("delete"));
        if (username.equals("admin")){
            list.add(new SimpleGrantedAuthority("ROLE_admin"));
        }

        UserDetails userDetails = new User(username,password,list);
        return userDetails;
    }
}
